package cn.itsource.basic.service.impl;

import cn.itsource.basic.mapper.BaseMapper;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.service.IBaseService;

import cn.itsource.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;


@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class BaseServiceImpl<T> implements IBaseService<T>{

    @Autowired
    private BaseMapper<T> baseMapper;

    @Override
    @Transactional
    public void saveOrUpdate(T t) {
        /*
            1.方案一 ，多加一个参数
            2.通过反射 调用
        */
        Class<?> cla = t.getClass();
        Object o = null;
        try {
            // 获取类型里面的getId的方法
            Method getId = cla.getMethod("getId");
            //执行getId的方法  o  方法执行完成以后的返回值
            o = getId.invoke(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (o == null) {
            baseMapper.save(t);
        } else {
            baseMapper.update(t);
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        baseMapper.delete(id);
    }
    @Override
    public T loadById(Long id) {
        return baseMapper.loadById(id);
    }
    @Override
    public List<T> loadAll() {
        return baseMapper.loadAll();
    }
    @Override
    public PageList<T> page(BaseQuery query) {
        //计算总条数
        Long count = baseMapper.count(query);
        List<T> list = null;
        if (count != null || count != 0) {
            list = baseMapper.queryPage(query);
        }
        return new PageList<>(count, list);
    }
}
